package org.mech.sefer.client.mvp.spring;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.config.BeanPostProcessor;

/**
 * <p>
 * The PresenterDestroyerBean is bean that tracks creation of prototype
 * presenter beans and on disposing calls preDestroy methods on them
 * </p>
 * <p>
 * Date: 24.4.2012 12:30:01
 * </p>
 * 
 * @author martin.krajc
 */
public class PresenterDestroyerBean implements DisposableBean,
		BeanPostProcessor {

	private List<AbstractSpringPresenter<?>> presentersToDestroy = new ArrayList<AbstractSpringPresenter<?>>();

	@Override
	public void destroy() throws Exception {
		if (!presentersToDestroy.isEmpty()) {
			for (AbstractSpringPresenter<?> presenter : presentersToDestroy) {
				presenter.preDestroy();
				System.out.println(presenter + " destroyed");
			}
		}
	}

	@Override
	public Object postProcessAfterInitialization(Object obj, String s)
			throws BeansException {
		if (obj instanceof AbstractSpringPresenter) {
			presentersToDestroy.add((AbstractSpringPresenter<?>) obj);
		}
		return obj;
	}

	@Override
	public Object postProcessBeforeInitialization(Object obj, String s)
			throws BeansException {
		return obj;
	}

}
